<template>
  <div>
    <el-dialog title="设置" :visible.sync="dialogVisible">
      <el-form
        ref="form"
        :model="websiteinfo"
        label-width="100px"
        :rules="rules"
      >
      <!--
        <el-form-item prop="siteLogo" label="Logo：">
          <uploadImg
            @image-uploaded="handleImageUploadedLogo"
            :sitePic="websiteinfo.siteLogo"
            :disabled="false"
          />
        </el-form-item>
      -->
        
      <el-form-item prop="siteLogo" label="Logo：">
        <el-upload :disabled="websiteInfo.siteLogo !== null&&websiteInfo.siteLogo !== ''" :file-list="siteLogoList" :multiple="false" drag ref="uploadCoverLogo"
          action="#" list-type="picture" :auto-upload="false" class="upload" accept="image/*" :on-change="handleChangeLogo"
          :on-remove="handleRemoveLogo">
          <div v-if="websiteInfo.siteLogo === ''" style="display: flex;flex-direction: column;align-items: center;">
            <img :src="require('@/assets/article/uploadimage.png')" alt="Upload Image" class="upload_image" />
            <div class="el-upload__text upload_tip">
              拖拽图片到此区域也可上传<span><em>上传</em>一张不超过 2MB 的image/*文件</span>
            </div>
          </div>
          <div v-else class="url_image">
            <el-image :preview-src-list="[websiteInfo.siteLogo.url||websiteInfo.siteLogo]" :src="websiteInfo.siteLogo.url||websiteInfo.siteLogo" class="url_img" ref="urlImg"></el-image>
            <div class="url_drow">
              <i class="el-icon-delete" @click.stop="handleRemoveLogo"></i>
              <i class="el-icon-zoom-in" @click="handlePreview($refs.urlImg)"></i>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item prop="sitePic" label="网站图片：">
        <el-upload :disabled="websiteInfo.sitePic !== null&&websiteInfo.sitePic !== ''" :file-list="sitePicList" :multiple="false" drag ref="uploadCover"
          action="#" list-type="picture" :auto-upload="false" class="upload" accept="image/*" :on-change="handleChange"
          :on-remove="handleRemove">
          <div v-if="websiteInfo.sitePic === ''" style="display: flex;flex-direction: column;align-items: center;">
            <img :src="require('@/assets/article/uploadimage.png')" alt="Upload Image" class="upload_image" />
            <div class="el-upload__text upload_tip">
              拖拽图片到此区域也可上传<span><em>上传</em>一张不超过 2MB 的image/*文件</span>
            </div>
          </div>
          <div v-else class="url_image">
            <el-image :preview-src-list="[websiteInfo.sitePic.url||websiteInfo.sitePic]" :src="websiteInfo.sitePic.url||websiteInfo.sitePic" class="url_img" ref="urlPic"></el-image>
            <div class="url_drow">
              <i class="el-icon-delete" @click.stop="handleRemove"></i>
              <i class="el-icon-zoom-in" @click="handlePreview($refs.urlPic)"></i>
            </div>
          </div>
        </el-upload>
      </el-form-item>
        <el-form-item prop="siteName" label="子页面名：">
          <el-input v-model.trim="websiteinfo.siteName" style="width: 80%" />
        </el-form-item>
        <!--
        <el-form-item prop="sitePic" label="子页面图片：">
          <uploadImg
            @image-uploaded="handleImageUploadedPic"
            :sitePic="websiteinfo.sitePic"
            :disabled="false"
          />
        </el-form-item>
      -->
        <el-form-item prop="siteUrl" label="子页面路径：">
          <el-input
            v-model.trim="websiteinfo.siteUrl"
            style="width: 80%"
            :disabled="isSiteUrlDisabled"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSubpage, editSubpage } from "@/api/api.js";
import uploadImg from "./uploadImg.vue";
import { getFolderId,fileUpload } from '@/api/api' // 引入api文件
export default {
  data() {
    return {
      siteLogoList:[],//中转用的logo图片
      sitePicList:[],//中转用的网站图片

      dialogVisible: this.dialogFormVisible, // 本地变量来管理弹窗的可见性
      websiteinfo: this.websiteInfo,
      rules: {
        siteLogo: [
          { required: true, message: "Logo不能为空", trigger: "blur" },
        ],
        siteName: [
          { required: true, message: "网站名不能为空", trigger: "blur" },
        ],
        sitePic: [
          { required: true, message: "网站图片不能为空", trigger: "blur" },
        ],
        siteUrl: [
          { required: true, message: "网站链接不能为空", trigger: "blur" },
        ],
      },
      isSiteUrlDisabled: false,
    };
  },

  props: {
    dialogFormVisible: Boolean,
    websiteInfo: Object,
    mainPageId: String,
    getSubpageInfo: Function,

    
    
  },

  watch: {
    dialogFormVisible(newValue) {
      this.dialogVisible = newValue;
    },
    dialogVisible(newValue) {
      this.$emit("update:dialogFormVisible", newValue);
    },
    websiteInfo: {
      handler(newValue) {
        this.websiteinfo = newValue;
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    async submitDialog() {
      await this.$refs.form.validate(async (valid) => {
        if (valid) {
          
          if (this.websiteinfo.id && this.websiteinfo.id !== "") {
            try {
              const res = await editSubpage(this.websiteinfo);
              this.$emit("refresh");
              this.$message({
                message: res.data.message,
                type: res.data.code === 200 ? "success" : "error",
              });
            } catch (error) {
              console.error(error);
            } finally {
              this.dialogVisible = false;
            }
          } else {
            try {
              this.websiteinfo.siteId = this.mainPageId;
              const res = await addSubpage(this.websiteinfo);
              this.$emit("refresh");
              this.$message({
                message: res.data.message,
                type: res.data.code === 200 ? "success" : "error",
              });
              // 清空表单
              this.websiteinfo = {
                siteLogo: "",
                siteName: "",
                sitePic: "",
                siteUrl: "",
                siteLogoList:[],//中转用的logo图片
                sitePicList:[],//中转用的网站图片
              };
            } catch (error) {
              console.error(error);
            } finally {
              this.dialogVisible = false;
            }
          }
        } else {
          this.$message({ message: "请填写完整", type: "error" });
        }
      });
    },
    cancelDialog() {
      this.dialogVisible = false;
    },
    handleImageUploadedLogo(url) {
      this.websiteinfo.siteLogo = url;
    },
    handleImageUploadedPic(url) {
      this.websiteinfo.sitePic = url;
    },

    // 上传文件
    async uploadFile(file){
      const filderId = await this.getFolderId();
      const formData = new FormData();
      formData.append('file',file);
      formData.append('folderId',filderId);
      formData.append('isCover',"0");
      // 下面返回上传路径
      return await fileUpload(formData).then(resp => {
        if(resp.data.code == 200){
          return resp.data.result.src;
        }else{throw new Error('上传失败');}
      }).catch(e => {throw new Error('处理失败');})
    },

    // 获取文件夹id
    async getFolderId(){
      return getFolderId({
        folderName: "官网",
        folderDescribe: "官网目录自动创建",
        folderAttributes: '{"dataType":0}',
      }).then(resp => {
        if(resp.data.code == 200){
          return resp.data.result;
        }else{this.$message.error('文件夹路径获取失败！')}
      }).catch(e => {this.$message.error('处理失败！')})
    },

    //图片的上传
    handleChange(file, fileList) {
      this.$refs.uploadCover.clearFiles();
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB');
        return;
      }
      let isAccept = new RegExp('image/*').test(file.raw.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件');
        return;
      }
      this.websiteInfo.sitePic = file;
      this.sitePicList[0] = file;
    },
     // 删除文件
     handleRemove(file, fileList) {
      const el = this.$refs.urlPic.$el;
      el.classList.add('flipOutX');
      setTimeout(() => {
        // 移除效果
        el.classList.remove('flipOutX');
        this.websiteInfo.sitePic = '';
        this.sitePicList = [];
        this.$refs.uploadCover.clearFiles();
      }, 500);
    },

    handlePreview(img) {
      img.showViewer = true;
    },


    //logo的上传
    handleChangeLogo(file, fileList) {
      this.$refs.uploadCoverLogo.clearFiles();
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB');
        return;
      }
      let isAccept = new RegExp('image/*').test(file.raw.type)
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件');
        return;
      }
      this.websiteInfo.siteLogo = file;
      this.sitePicList[0] = file;
    },
    // 删除文件
    handleRemoveLogo(file, fileList) {
      const el = this.$refs.urlImg.$el;
      el.classList.add('flipOutX');
      setTimeout(() => {
        // 移除效果
        el.classList.remove('flipOutX');
        this.siteLogoList = [];
        this.$refs.uploadCoverLogo.clearFiles();
        this.websiteInfo.siteLogo = '';
      }, 500);
    },

  },
  components: {
    uploadImg,
  },
};
</script>
<style scoped>
.el-button--primary {
  background-color: rgb(126, 114, 242);
  border-color: #7e72f2;
}

.el-button--primary:hover {
  background-color: rgba(126, 114, 242, 0.5);
}

.upload>>>.el-upload-dragger {
  opacity: 1;
  border-radius: 10px;
  background: rgba(253, 252, 255, 1);
  border: 1px dashed rgba(126, 114, 242, 1);
  /* z-index: 1; */
}

.upload>>>.el-upload--picture-card {
  width: auto;
  border-radius: 10px;
  height: auto;
}
 
.upload {
  position: relative;
  height: 170px;
  /* z-index: 1; */
}

.upload_image {
  width: 50px;
  height: 50px;
  margin-top: 30px;
}

.upload_content {
  display: flex;
  flex-direction: column;

}

.upload_tip {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  line-height: 20px;
  justify-content: center;
}

.url_drow {
  display: none;
  color: white;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: default;
  position: absolute;
  background-color: rgba(118, 116, 116, 0.589);
  justify-content: center;
  align-items: center;
  font-size: 25px;
}
 
.url_drow i {
  cursor: pointer;
  margin-left: 5px;
  margin-right: 5px;
}

.url_drow i:hover {
  color: rgb(126, 114, 242);
}

.url_image:hover .url_drow {
  display: flex;
}

.url_img {
  width: 100%;
  height: 180px;
  animation-duration: 0.5s;
  animation-fill-mode: both;
  animation-name: fadeInDown;
  backface-visibility: visible !important;
}
@keyframes fadeInDown {
    from {
        transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
        animation-timing-function: ease-in;
        opacity: 0;
    }

    40% {
        transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
        animation-timing-function: ease-in;
    }

    60% {
        transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
        opacity: 1;
    }

    80% {
        transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
    }

    to {
        transform: perspective(400px);
    }
}
@keyframes flipOutX {
    from {
        transform: perspective(400px);
    }

    30% {
        transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
        opacity: 1;
    }

    to {
        transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
        opacity: 0;
    }
}

.flipOutX {
    animation-duration: calc(0.8s * 0.75);
    animation-name: flipOutX;
    backface-visibility: visible !important;
}
</style>